﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace TextImageMerge
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnBuilder_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            int width = int.Parse(txtWidth.Text);
            int height = int.Parse(txtHeight.Text);
            string savePath = GetAbsPath(txtSavePath.Text);
            if (!Directory.Exists(savePath))
            {
                if (txtSavePath.Text == @"\export\")
                    Directory.CreateDirectory(savePath);
                else
                {
                    MessageBox.Show($"输出路径{savePath}不存在！");
                    return;
                }
            }
            string bg = GetAbsPath(txtBg.Text);
            Color bgColor;
            Brush bgBrush = null;
            Color textColor = ColorTranslator.FromHtml(txtTextColor.Text);

            Font font = fontDialog1.Font;
            Brush brush = new SolidBrush(textColor);
            if (txtBgColor.Text != "")
            {
                bgColor = ColorTranslator.FromHtml(txtBgColor.Text);
                bgBrush = new SolidBrush(bgColor);
            }

            Bitmap bitmap = new Bitmap(width, height);
            StringFormat strinFormat = new StringFormat();
            strinFormat.Alignment = StringAlignment.Center;
            Image bgImg = null;
            if (bg != "")
                bgImg = Image.FromFile(bg);

            List<string> list = GetList();
            foreach (string item in list)
            {
                Size size = TextRenderer.MeasureText(item, font);

                bitmap = new Bitmap(width, height);
                Graphics g = Graphics.FromImage(bitmap);

                g.InterpolationMode = InterpolationMode.HighQualityBicubic;//设置高质量插值法
                g.SmoothingMode = SmoothingMode.HighQuality;               //设置高质量,低速度呈现平滑程度 
                g.CompositingQuality = CompositingQuality.HighQuality;     //高质量、低速度复合
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.TextRenderingHint = TextRenderingHint.AntiAlias;          //消除锯齿

                if (bgImg != null)
                    g.DrawImage(bgImg, 0, 0, width, height);
                else if (bgBrush != null)
                    g.FillRectangle(bgBrush, 0, 0, width, height);

                g.DrawString(item, font, brush, new Rectangle(0, (height - size.Height) / 2, width, height), strinFormat);
                // g.Clear(Color.Transparent);
                g.Save();
                g.Dispose();
                if (chkPng.Checked)
                {
                    bitmap.MakeTransparent(Color.Transparent);
                    bitmap.Save($"{savePath}\\{item}.png", ImageFormat.Png);
                }
                else
                {
                    bitmap.Save($"{savePath}\\{item}.jpg", ImageFormat.Jpeg);
                }
            }
            lblMsg.Text = "生成成功.";
        }

        private List<string> GetList()
        {
            List<string> list = new List<string>();
            if (rdoSource2.Checked)
            {
                list = txtNumbers.Lines.Where(m => m.Trim().Length > 0).ToList();
            }
            else
            {
                int begin = int.Parse(txtBegin.Text);
                int end = int.Parse(txtEnd.Text);
                int maxLength = txtEnd.Text.Trim().Length;
                for (int i = begin; i <= end; i++)
                {
                    list.Add(i.ToString().PadLeft(maxLength, '0'));
                }
            }
            return list;
        }

        private void btnFont_Click(object sender, EventArgs e)
        {
            fontDialog1.ShowDialog(this);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lblMsg.Text = string.Empty;
            fontDialog1.Font = new Font("微软雅黑", 100, FontStyle.Bold);
            colorDialog1.Color = Color.Black;
            LoadConfig();
        }

        private void btnColor_Click(object sender, EventArgs e)
        {
            SetColor(txtTextColor);
        }

        private void btnBgColor_Click(object sender, EventArgs e)
        {
            SetColor(txtBgColor);
        }

        private void SetColor(Control target)
        {
            if (colorDialog1.ShowDialog(this) == DialogResult.OK)
            {
                target.Text = ColorTranslator.ToHtml(colorDialog1.Color);
            }
        }

        private void btnBrowser_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
                txtBg.Text = openFileDialog1.FileName;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK)
                txtSavePath.Text = folderBrowserDialog1.SelectedPath;
        }

        private void btnOpenSavePath_Click(object sender, EventArgs e)
        {
            string file = GetAbsPath(txtSavePath.Text);

            try
            {
                Clipboard.SetData(DataFormats.Text, file);
                System.Diagnostics.Process.Start("Explorer.exe", @"/select," + file);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "\r\n因权限问题，不能打开文件夹，已将目录(" + file + ")复制到粘贴板，请粘贴到地址栏中打开！");
            }
        }

        private string GetAbsPath(string virPath)
        {
            if (string.IsNullOrEmpty(virPath))
                return string.Empty;
            return virPath.IndexOf(':') == -1 ? Path.Combine(Application.StartupPath, virPath.TrimStart('\\', '\\')) : virPath;
        }

        #region SaveConfig

        private SettingInfo BindInfo()
        {
            SettingInfo info = new SettingInfo();
            info.Bg = txtBg.Text.Trim();
            info.BgColor = txtBgColor.Text.Trim();
            info.FontName = fontDialog1.Font.Name;
            info.FontSize = fontDialog1.Font.Size;
            info.FontStyle = (int)fontDialog1.Font.Style;
            info.TextColor = txtTextColor.Text.Trim();
            info.BeginNumber = int.Parse(txtBegin.Text.Trim());
            info.EndNumber = int.Parse(txtEnd.Text.Trim());
            info.Width = int.Parse(txtWidth.Text.Trim());
            info.Height = int.Parse(txtHeight.Text.Trim());
            info.SavePath = txtSavePath.Text.Trim();
            info.IsPng = chkPng.Checked;
            info.DataSource = txtNumbers.Lines;
            info.DataSourceType = rdoSource2.Checked ? 2 : 1;
            return info;
        }

        private void ShowInfo(SettingInfo info)
        {
            txtBg.Text = info.Bg;
            txtBgColor.Text = info.BgColor;
            txtTextColor.Text = info.TextColor;
            info.FontStyle = (int)fontDialog1.Font.Style;
            txtBegin.Text = info.BeginNumber.ToString();
            txtEnd.Text = info.EndNumber.ToString();
            txtWidth.Text = info.Width.ToString();
            txtHeight.Text = info.Height.ToString();
            txtSavePath.Text = info.SavePath;
            chkPng.Checked = info.IsPng;
            txtNumbers.Lines = info.DataSource;
            fontDialog1.Font = new Font(info.FontName, info.FontSize, (FontStyle)info.FontStyle);
            openFileDialog1.InitialDirectory = string.IsNullOrEmpty(info.OpenDialogInitDir) ? openFileDialog1.InitialDirectory : info.OpenDialogInitDir;
            saveFileDialog1.InitialDirectory = string.IsNullOrEmpty(info.SaveDialogInitDir) ? saveFileDialog1.InitialDirectory : info.OpenDialogInitDir;
            rdoSource1.Checked = info.DataSourceType <= 1;
            rdoSource2.Checked = info.DataSourceType == 2;
        }
        #endregion

        #region 打开/保存

        private void mnuOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "json|*.json";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                LoadConfig(openFileDialog.FileName);
            }
        }

        private string curruntFilePath = null;
        private void mnuSave_Click(object sender, EventArgs e)
        {
            if (curruntFilePath != null)
                SaveConfig(curruntFilePath);
            else
                mnuSaveAs_Click(sender, e);
        }

        private void mnuSaveAs_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                curruntFilePath = saveFileDialog1.FileName;
                mnuSave_Click(sender, e);
            }
        }
        #endregion
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveConfig();
        }

        #region MyRegion

        private void LoadConfig(string path = null)
        {
            try
            {
                if (path == null)
                    path = GetAbsPath("data.json");
                if (!File.Exists(path))
                    return;
                curruntFilePath = path;
                SettingInfo info = JsonHelper.ReadJson<SettingInfo>(path);
                ShowInfo(info);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void SaveConfig(string path = null)
        {
            try
            {
                if (path == null)
                    path = GetAbsPath("data.json");
                SettingInfo info = BindInfo();
                JsonHelper.WriteJson(info, path);
                curruntFilePath = path;
                lblMsg.Text = "保存成功";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        #endregion

        private void frmMain_KeyUp(object sender, KeyEventArgs e)
        {
            lblMsg.Text = "";
            if (e.Control && e.KeyCode == Keys.S)
                SaveConfig();
            else if (e.Control && e.Shift && e.KeyCode == Keys.S)
                mnuSaveAs_Click(null, null);
            else if (e.Control && e.KeyCode == Keys.O)
                mnuOpen_Click(null, null);
        }

        private void rdoSource1_CheckedChanged(object sender, EventArgs e)
        {
            txtBegin.Enabled = rdoSource1.Checked;
            txtEnd.Enabled = rdoSource1.Checked;
            txtNumbers.Enabled = !rdoSource1.Checked;
        }

        private void tooHelp_Click(object sender, EventArgs e)
        {
            MessageBox.Show("软件问题QQ:5079512");
        }
    }
}
